/*
 * Filename:    IntrgityBlackController.java
 * Copyright:   2014 中国平安保险（集团）股份有限公司 版权所有
 * Company:     平安科技养老险及健康险系统开发部
 * Create at:   2014年10月30日
 */
package com.paic.mhis.hcpms.trust.web.controller;

import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.paic.mhis.core.auth.biz.service.UserDetails;
import com.paic.mhis.hcpms.quota.settlement.biz.service.KpiRegionCodeService;
import com.paic.mhis.hcpms.trust.biz.service.IntegrityBusinessService;
import com.paic.mhis.hcpms.trust.common.ConstantsUtils;
import com.paic.mhis.hcpms.trust.common.TrustConstants;
import com.paic.mhis.hcpms.trust.dto.BlackParamterCondtion;
import com.paic.mhis.hcpms.trust.dto.BlackPatientBaseInfoDTO;
import com.paic.mhis.hcpms.trust.dto.IntegrityBlackDTO;
import com.paic.mhis.hcpms.trust.dto.IntegrityBlackOpinionDTO;
import com.paic.mhis.hcpms.trust.intergration.dao.IntegrityBlackDao;
import com.paic.mhis.hcpms.trust.web.vo.HhAlertMessage;
import com.paic.mhis.hcpms.trust.web.vo.IntegrityResponseBean;
import com.paic.mhis.hcpms.trust.web.vo.InterityBlackAddRequestVO;
import com.paic.pafa.appclient.annotation.BizServicesProxy;

/**
 * 参保人诚信管理审核岗位的controller
 * 
 * @author EX-WANGKUI001
 * 
 */
@Controller
@RequestMapping("/integrityBlackAudit/")
public class IntrgityBlackAuditController {
	public static Log log = LogFactory.getLog(IntrgityBlackAuditController.class);

	@BizServicesProxy(beanName = "integrityBusinessServiceImpl")
	private IntegrityBusinessService service;

	@BizServicesProxy(beanName = "integrityBlackDaoImpl")
	private IntegrityBlackDao integrityBlackDao;

	@BizServicesProxy(beanName = "kpiRegionCodeService")
	private KpiRegionCodeService kpiRegionCodeService;

	public static final String fileNamePath = "views/hcpms/achievements/integrity/参保人诚信管理导入Excel模板.xls";
	public static final String fileName = "参保人诚信管理导入Excel模板.xls";

	private String filePath;

	@RequestMapping("loadBlackExcelFile.do")
	@ResponseBody
	public void loadBlackExcelFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String path = filePath + fileName;

		log.info("current path==" + path);

		BufferedOutputStream bos = null;
		String disposition = "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8");
		response.setHeader("Content-disposition", disposition);
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(path);
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buffer = new byte[2048];
			while (fis.read(buffer) != -1) {
				bos.write(buffer);
				bos.flush();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				fis.close();
			}
			if (bos != null) {
				bos.close();
			}
		}

	}

	/**
	 * 加载所有的参保黑名单信息
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("checkPatientBasicExist.do")
	@ResponseBody
	public IntegrityResponseBean loadAllBlackPerson(HttpServletRequest request) {

		IntegrityResponseBean responseBean = new IntegrityResponseBean();
		String personCard = request.getParameter("personCard");
		boolean flag = this.service.processCheckBlackExist(personCard);
		responseBean.setStatus(flag);
		return responseBean;
	}

	/**
	 * 加载所有的参保黑名单信息
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("loadAllBlackPerson.do")
	@ResponseBody
	public IntegrityResponseBean loadAllBlackPerson(@ModelAttribute InterityBlackAddRequestVO vo,
			HttpServletRequest request) {
		IntegrityResponseBean bean = new IntegrityResponseBean();

		BlackParamterCondtion parameter = new BlackParamterCondtion();
		String name = vo.getName();
		String cardNo = vo.getCardNo(); // /身份证号
		String personNo = vo.getPersonCard(); // 社保号
		String personType = vo.getPersonType(); // 人员类别

		int page = vo.getPage();
		int pageSize = vo.getPageSize();

		int start = (page - 1) * pageSize;
		int end = start + pageSize;

		parameter.setStart(start);
		parameter.setEnd(end);

		if (StringUtils.hasText(name)) {
			parameter.setName("%" + name + "%");
		}
		if (StringUtils.hasText(personNo)) {
			parameter.setPersonCard("%" + personNo + "%");
		}
		if (StringUtils.hasText(personType)) {
			parameter.setPersonType(personType);
		}
		if (StringUtils.hasText(cardNo)) {
			parameter.setCardNo("%" + cardNo + "%");
		}

		List<BlackPatientBaseInfoDTO> list = this.service.queryBlackPatientBaseInfoDTO(parameter);
		long count = this.service.queryBlackPaientBaseInfoCount(parameter);

		bean.setStatus(true);
		bean.setPatientList(list);
		bean.setTotal(count);

		return bean;
	}

	/**
	 * 根据社保号加载社保人员信息
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("loadPatientBasicInfo.do")
	@ResponseBody
	public IntegrityResponseBean loadPatientBasicInfo(@ModelAttribute InterityBlackAddRequestVO vo,
			HttpServletRequest request) {
		String personCard = vo.getPersonCard(); // 社保号
		IntegrityResponseBean returnBean = new IntegrityResponseBean();

		if (StringUtils.hasText(personCard)) {

			IntegrityBlackDTO bean = this.service.getIntegrityBlackDTOBySociationNum(personCard);
			if (bean != null) {
				List<IntegrityBlackDTO> list = new ArrayList<IntegrityBlackDTO>();
				list.add(bean);

				returnBean.setStatus(true);
				returnBean.setResult(list);
			} else {
				returnBean.setStatus(false);
			}

		} else {
			returnBean.setStatus(false);
		}
		return returnBean;
	}

	/**
	 * 上传参保人信息
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("uploadIntegrityBlackExcel.do")
	@ResponseBody
	public Map<String, Object> uploadIntegrityBlackExcel(@ModelAttribute InterityBlackAddRequestVO vo,
			HttpServletRequest request) {
		UserDetails user = (UserDetails) request.getSession().getAttribute("user");
		String username = user.getUsername();
		String regionCode = this.kpiRegionCodeService.getRegionCode(user.getUserId());

		IntegrityResponseBean returnBean = new IntegrityResponseBean();
		MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		MultipartHttpServletRequest multiRequest = resolver.resolveMultipart(request);

		List<MultipartFile> files = multiRequest.getFiles("file");
		List<IntegrityBlackDTO> list = null;
		List<Object> liP = new ArrayList<Object>();

		if (files != null && files.size() > 0) {

			for (MultipartFile file : files) {
				try {
					InputStream is = file.getInputStream();
					HSSFWorkbook wb = new HSSFWorkbook(is);

					int sheetNum = wb.getNumberOfSheets(); // 获取sheet
					for (int i = 0; i < sheetNum; i++) {
						HSSFSheet childSheet = wb.getSheetAt(i);
						int rowNum = childSheet.getLastRowNum();

						// j=1 跳过head部分
						for (int j = 1; j <= rowNum; j++) {
							list = new ArrayList<IntegrityBlackDTO>();
							HSSFRow row = childSheet.getRow(j);

							IntegrityBlackDTO currentBean = this.getIntegrityBlackDTOFromRow(row, username);
							currentBean.setRegionCode(regionCode);
							currentBean.setfJFileName(file.getOriginalFilename());
							currentBean.setfJRowNum(j);
							list.add(currentBean);

							liP.add(list);
						}
					}
				} catch (Exception e) {

					returnBean.setStatus(false);
					returnBean.setMessage("上传失败" + e.getCause().getMessage());

					log.info("**************black upload error********" + e.getMessage());
				}
			}
		}

		Map<String, Object> hhamap = new HashMap<String, Object>();
		List<HhAlertMessage> hhalist = new ArrayList<HhAlertMessage>();

		for (int i = 0; i < liP.size(); i++) {
			List<IntegrityBlackDTO> lists = (List<IntegrityBlackDTO>) liP.get(i);
			// 处理保存
			if (lists != null && lists.size() > 0) {
				String checkSql = this.checkExcelFile(lists);
				if (StringUtils.hasText(checkSql)) {

					HhAlertMessage hhvo = new HhAlertMessage();
					String mags = "消息：上传失败，附件名：" + lists.get(0).getfJFileName() + "，行号：" + lists.get(0).getfJRowNum()
							+ "，备注：" + checkSql + "";
					hhvo.setMes(mags);
					hhalist.add(hhvo);
				} else {

					this.service.processIntegrityBeanList(lists);
				}
			}
		}

		hhamap.put("hhmapData", hhalist);

		HhAlertMessage hhvok = new HhAlertMessage();
		hhvok.setMes("上传成功");

		List<HhAlertMessage> hhalistok = new ArrayList<HhAlertMessage>();
		hhalistok.add(hhvok);
		hhamap.put("hhmapDataOk", hhalistok);

		return hhamap;
	}

	/**
	 * 校验上传的excel是否格式正确
	 * 
	 * @param list
	 * @return
	 */
	private String checkExcelFile(List<IntegrityBlackDTO> list) {
		StringBuffer sql = new StringBuffer();
		if (list != null && list.size() > 0) {

			for (IntegrityBlackDTO bean : list) {
				String name = bean.getName();
				String gender = bean.getGender();
				String cardType = bean.getCardType();
				String cardNo = bean.getCardNo();
				String personCard = bean.getPersonCard();
				String inBlackReason = bean.getInBlackReason();
				Date happenDate = bean.getHappenDate();
				Date startDate = bean.getStartDate();
				Date endDate = bean.getEndDate();

				if (!StringUtils.hasText(name)) {
					sql.append("姓名不能为空！");
					break;
				}

				if (!StringUtils.hasText(gender)) {
					sql.append("性别不能为空！");
					break;
				}
				if (!StringUtils.hasText(cardType)) {
					sql.append("证件类型不能为空！");
					break;
				}
				if (!StringUtils.hasText(cardNo)) {
					sql.append("证件号不能为空！");
					break;
				}

				if (!StringUtils.hasText(personCard)) {
					sql.append("保险号不能为空！");
					break;
				} else {
					IntegrityBlackDTO currentBean = this.service.getIntegrityBlackDTOBySociationNum(personCard);
					if (currentBean == null) {
						sql.append("保险号[" + personCard + "]不存在！");
						break;
					}
				}

				if (!StringUtils.hasText(inBlackReason)) {
					sql.append("进入黑名单原因不能为空！");
					break;
				}

				if (happenDate == null) {
					sql.append("案发时间不能为空！");
					break;
				}
				if (startDate == null) {
					sql.append("有效开始时间不能为空！");
					break;
				}
				if (endDate == null) {
					sql.append("有效结束时间不能为空！");
					break;
				}

			}
		}

		return sql.toString();

	}

	private IntegrityBlackDTO getIntegrityBlackDTOFromRow(HSSFRow row, String opertionUser) {

		if (row != null) {
			IntegrityBlackDTO bean = new IntegrityBlackDTO();
			int cellNum = row.getLastCellNum(); // 每行有多少列(格)
			for (int k = 0; k < cellNum; k++) // 此循环用来规范数据,如果某个格子里没有数据为空,
												// // 则替换成--
			{
				String value = "";
				if (row.getCell(k) != null) {
					value = row.getCell(k).toString();
				} else {
					continue;
				}

				if (!StringUtils.hasText(value)) {
					continue;
				}

				if (k == 0) { // name
					bean.setName(value);
				}

				if (k == 1) { // 姓名简拼
					bean.setAlPhabetic(value);
				}
				if (k == 2) { // gender
					if (value.equals("男")) {
						bean.setGender("M");
					} else if (value.equals("女")) {
						bean.setGender("F");
					}
				}

				if (k == 3) { // 证件类型
					if (value.equals("身份证")) {
						bean.setCardType("1");
					} else if (value.equals("军官证")) {
						bean.setCardType("3");
					} else if (value.equals("护照")) {
						bean.setCardType("2");
					} else if (value.equals("少儿证")) {
						bean.setCardType("4");
					} else if (value.equals("台胞证")) {
						bean.setCardType("5");
					} else if (value.equals("港澳台通行证")) {
						bean.setCardType("6");
					} else if (value.equals("其他")) {
						bean.setCardType("9");
					} else if (value.equals("转换不详")) {
						bean.setCardType("8");
					}
				}

				if (k == 4) { // 证件号
					bean.setCardNo(value);
				}
				if (k == 5) { // 社保号
					bean.setPersonCard(value);
				}
				if (k == 6) { // 案发时间

					Date date = ConstantsUtils.getStringFormateDate(value);
					bean.setHappenDate(date);
				}
				if (k == 7) { // 进入黑名单原因

					bean.setInBlackReason(value);
				}
				if (k == 8) { // 有效时间开始
					Date startDate = ConstantsUtils.getStringFormateDate(value);
					bean.setStartDate(startDate);
				}
				if (k == 9) {// 有效结束时间
					Date endDate = ConstantsUtils.getStringFormateDate(value);
					bean.setEndDate(endDate);
				}

			}

			bean.setCreateDate(new Date());
			bean.setOpertionUser(opertionUser);
			bean.setUpdateDate(new Date());
			bean.setStatus(TrustConstants.status_01);
			return bean;
		} else {
			return null;
		}

	}

	/**
	 * 查询参保人信息
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("queryIntegrityBlackData.do")
	@ResponseBody
	public IntegrityResponseBean queryIntegrityBlackData(@ModelAttribute InterityBlackAddRequestVO vo,
			HttpServletRequest request) {

		BlackParamterCondtion condition = new BlackParamterCondtion();
		String name = vo.getName();

		String processState = vo.getProcessState();

		String currentName = ConstantsUtils.processSqlName(name);

		String personCard = vo.getPersonCard();
		int page = vo.getPage();
		int pageSize = vo.getPageSize();

		int start = (page - 1) * pageSize;
		int end = start + pageSize;

		condition.setStart(start);
		condition.setEnd(end);
		condition.setName(currentName);
		if (StringUtils.hasText(personCard)) {
			condition.setPersonCard("%" + personCard + "%");
		}
		if (StringUtils.hasText(processState)) {
			condition.setProcessState(processState);
		}
		condition.setHappenDateStart(vo.getStartDate());
		condition.setHappenDateEnd(vo.getEndDate());
		condition.setCreateStartDate(vo.getCreateStartDate());
		condition.setCrateEndDate(vo.getCrateEndDate());
		condition.setSwiftCode(vo.getSwiftCode());
		
		IntegrityResponseBean bean = new IntegrityResponseBean();

		List<IntegrityBlackDTO> list = this.service.queryIntegrityBlackDTO(condition);
		long count = this.service.queryIntegrityBlackDTOCount(condition);
		bean.setResult(list);
		bean.setTotal(count);
		return bean;
	}

	/**
	 * 获取登陆系统的用户信息
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("initDataUser.do")
	@ResponseBody
	public IntegrityResponseBean initDataUser(@ModelAttribute InterityBlackAddRequestVO vo, HttpServletRequest request) {
		UserDetails user = (UserDetails) request.getSession().getAttribute("user");

		IntegrityResponseBean returnBean = new IntegrityResponseBean();
		returnBean.setMessage(user.getUsername());
		return returnBean;
	}

	@RequestMapping("updateIntegrityBlack.do")
	@ResponseBody
	public IntegrityResponseBean updateIntegrityBlack(@ModelAttribute InterityBlackAddRequestVO vo,
			HttpServletRequest request) {
		UserDetails user = (UserDetails) request.getSession().getAttribute("user");

		IntegrityBlackDTO bean = new IntegrityBlackDTO();
		bean.setName(vo.getName());
		bean.setGender(vo.getGender());
		bean.setCardNo(vo.getCardNo());
		bean.setCardType(vo.getCardType());

		bean.setInBlackReason(vo.getInBlackReason());
		bean.setPersonCard(vo.getPersonCard());
		bean.setStatus(TrustConstants.status_01);
		bean.setUpdateDate(new Date());
		bean.setOpertionUser(user.getUsername());

		String startStr = vo.getStartDate();
		String endStr = vo.getEndDate();
		String happenDateStr = vo.getHappenDate();

		Date startDate = ConstantsUtils.getStringFormateDate(startStr);
		Date endDate = ConstantsUtils.getStringFormateDate(endStr);

		Date happenDate = ConstantsUtils.getStringFormateDate(happenDateStr);

		bean.setStartDate(startDate);
		bean.setEndDate(endDate);
		bean.setHappenDate(happenDate);
		bean.setId(vo.getId());
		bean.setPhoneNumber(vo.getPhoneNumber());
		bean.setMobileNumber(vo.getMobileNumber());
		bean.setProcessState(TrustConstants.process_state_01);
		bean.setAttentionMidId(vo.getAttentionMidId());
		IntegrityResponseBean returnBean = new IntegrityResponseBean();
		try {
			this.service.updateIntegrityBlackDTO(bean);
			returnBean.setStatus(true);
			returnBean.setMessage(TrustConstants.REFRESH_SUCCESS);
		} catch (Exception es) {
			returnBean.setStatus(false);
			returnBean.setMessage(TrustConstants.REFRESH_FAILED);
			es.printStackTrace();
		}

		return returnBean;
	}

	/**
	 * 增加参保黑名单信息
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("addIntegrityBlack.do")
	@ResponseBody
	public IntegrityResponseBean addIntegrityBlack(@ModelAttribute InterityBlackAddRequestVO vo,
			HttpServletRequest request) {
		UserDetails user = (UserDetails) request.getSession().getAttribute("user");
		String regionCode = this.kpiRegionCodeService.getRegionCode(user.getUserId());
		IntegrityBlackDTO bean = new IntegrityBlackDTO();
		bean.setName(vo.getName());
		bean.setCreateDate(new Date());
		bean.setGender(vo.getGender());
		bean.setCardNo(vo.getCardNo());
		bean.setCardType(vo.getCardType());
		bean.setAlPhabetic(vo.getPingy());

		bean.setInBlackReason(vo.getInBlackReason());
		bean.setPersonCard(vo.getPersonCard());
		bean.setStatus(TrustConstants.status_01);
		bean.setUpdateDate(new Date());
		bean.setOpertionUser(user.getUsername());

		String startStr = vo.getStartDate();
		String endStr = vo.getEndDate();
		String happenDateStr = vo.getHappenDate();

		Date startDate = ConstantsUtils.getStringFormateDate(startStr);
		Date endDate = ConstantsUtils.getStringFormateDate(endStr);

		Date happenDate = ConstantsUtils.getStringFormateDate(happenDateStr);

		bean.setStartDate(startDate);
		bean.setEndDate(endDate);
		bean.setHappenDate(happenDate);
		bean.setRegionCode(regionCode);
		bean.setProcessState(TrustConstants.process_state_01);
		bean.setPhoneNumber(vo.getPhoneNumber());
		bean.setMobileNumber(vo.getMobileNumber());
		bean.setAttentionMidId(vo.getAttentionMidId());
		IntegrityResponseBean returnBean = new IntegrityResponseBean();
		try {
			this.service.saveIntegrityBean(bean);
			returnBean.setStatus(true);
			returnBean.setMessage(TrustConstants.SAVE_OR_UPDATE_SUCCESS);
		} catch (Exception es) {
			returnBean.setStatus(false);
			returnBean.setMessage(TrustConstants.SAVE_OR_UPDATE_FAILED);
			es.printStackTrace();
		}

		return returnBean;
	}

	@RequestMapping("initAttentionLevelList.do")
	@ResponseBody
	public List<Map<String, Object>> initAttentionLevelList(@ModelAttribute InterityBlackAddRequestVO vo,
			HttpServletRequest request) {

		List<Map<String, Object>> list = null;

		String attentionLevelId = vo.getAttentionLevelId();
		if (StringUtils.hasText(attentionLevelId)) {
			list = this.service.queryAttentionLevelInfo(TrustConstants.type_02, attentionLevelId);

		} else {
			list = this.service.queryAttentionLevelInfo(TrustConstants.type_01, "");
		}

		return list;

	}

	/**
	 * 审核参保人黑名单信息
	 * 
	 * @param vo
	 * @param request
	 * @return
	 */
	@RequestMapping("checkAuditBlackInfo.do")
	@ResponseBody
	public Map<String, Object> checkAuditBlackInfo(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			String[] codes = request.getParameterValues("codes");
			String opinion = request.getParameter("opinion");
			String opinionDesc = request.getParameter("opinionDesc");

			UserDetails user = (UserDetails) request.getSession().getAttribute("user");

			List<String> codeList = new ArrayList<String>();

			if (codes != null && codes.length > 0) {
				for (String code : codes) {
					codeList.add(code);
				}
			}

			map = this.service.processBlackAuditInfo(codeList, user, opinion, opinionDesc);
		} catch (Exception es) {
			map.put("flag", true);
			map.put("msg", es.getMessage());
			log.error(es.getMessage());
			log.error(es);
			es.printStackTrace();
		}

		return map;

	}

	/**
	 * 初始化审核页面的参保人黑名单信息
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("initAuditInfo.do")
	@ResponseBody
	public IntegrityBlackDTO initAuditInfo(HttpServletRequest request) {
		String id = request.getParameter("id");
		IntegrityBlackDTO bean = null;
		bean = this.service.getIntegrityBlackDTOById(id);
		return bean;

	}

	/**
	 * 根据id加载对应的审核意见
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("loadRebackReason.do")
	@ResponseBody
	public IntegrityBlackOpinionDTO loadRebackReason(HttpServletRequest request) {
		String id = request.getParameter("id");

		IntegrityBlackOpinionDTO bean = this.integrityBlackDao.queryAuditOpinion(id);
		return bean;

	}

}
